import ModelAbstract from './modelAbstract'
import { image } from '../service/image'
import bullet from '../canvas/bullet'
import config from '../config'
import { directionEnum } from '../enum/directionEnum'
import util from '../util'
import wall from '../canvas/wall'
import steel from '../canvas/steel'
import boss from '../canvas/boss'
import tank from '../canvas/tank'
import play from '../canvas/play'

export default class Bullet extends ModelAbstract implements IModel {
  public canvas: ICanvas = bullet
  name: string = 'bullet'
  constructor(public tank: IModel) {
    super(tank.x + config.model.width / 2, tank.y + config.model.height / 2)
    this.direction = tank.direction as unknown as directionEnum
  }
  image(): HTMLImageElement {
    return image.get('bullet')!
  }
  render() {
    let x = this.x
    let y = this.y
    const speed = this.tank.name === 'play' ? 10 : 5
    switch (this.direction) {
      case directionEnum.top:
        y -= speed
        break
      case directionEnum.right:
        x += speed
        break
      case directionEnum.bottom:
        y += speed
        break
      case directionEnum.left:
        x -= speed
        break
    }
    // 碰撞检测
    const touchModel = util.isModelTouch(x, y, 2, 2, [
      ...wall.models,
      ...steel.models,
      ...boss.models,
      ...tank.models,
      ...play.models
    ])
    if (util.isCanvasTouch(x, y, 2, 2)) {
      // 碰canvas边，销毁子弹
      this.destroy()
    } else if (touchModel && touchModel.name !== this.tank.name) {
      // 销毁子弹
      this.destroy()
      // 销毁碰撞的砖墙
      if (touchModel.name !== 'steel') touchModel.destroy()
      // 渲染爆炸
      this.blast(touchModel)
    } else {
      // 无碰撞
      this.x = x
      this.y = y
      this.draw()
    }
  }
  protected draw() {
    this.canvas.ctx.drawImage(this.image(), this.x, this.y, 2, 2)
  }
}
